(function() {
    'use strict';
    angular
    	.module('app')
    	.controller('mainCtrl', mainCtrl)
    	.directive('breadCrumbs',['$rootScope','$timeout','$compile',crumbCtrl])
    	.controller('ctrl.avater',['$scope','$uibModalInstance','$timeout','config','param','FileUploader','myUtils','http',avaterCtrl])
		.controller('ctrl.passWord',['$scope','$uibModalInstance','$timeout','config','param','myUtils','http',passWordCtrl]);
    	mainCtrl.$inject = ['$scope','$rootScope','$locale','$stateParams','$timeout','$uibModal','myUtils','http','config','common'];
      	function mainCtrl($scope,$rootScope,$locale,$stateParams,$timeout,$uibModal,myUtils,http,config,common) {
      		var vm = $scope.vm = {};
      		angular.extend( vm,{
      			showNav : true,
      			init : function(){
					// vm.localExtend();
      				// vm.time = parseInt($stateParams.remember) ? 7 : null;
      				// var token = myUtils.cookie('mxu_token');
      				// if( !token ){
      				// 	location.href= config.loginUrl;
      				// }
      				// if( !myUtils.storage.get('user_info')){
      				// 	/***判断登陆状态***/
      				// 	common.checke_user(function( data ){
		      		// 			if( data && data.error_message ){
		      		// 				var param= {
					// 					path   : window.CONFIG.cookiePath,
					// 					domain : window.CONFIG.cookieDomain
		      		// 				};
		      		// 				myUtils.cookie('mxu_token','',param);
		      		// 				$timeout(function(){
		      		// 					location.href= config.loginUrl;
		      		// 				});
		      		// 				return false;
		      		// 			}
		      		// 			if( data && data.id ){
		      		// 				if( data.avatar && data.avatar.filename ){
		      		// 					data.img = myUtils.createImgsrc(data.avatar,{
		      		// 						width:64,
		      		// 						height:64
		      		// 					});
		      		// 				}
		      		// 				vm.userInfo = data;
		      		// 				myUtils.storage.set('user_info',vm.userInfo,vm.time);
		      		// 			}
		      		// 		});
      				// }else{
      				// 	vm.userInfo = myUtils.storage.get('user_info');
      				// }
      				// vm.system = myUtils.storage.get('system_info');
      				// if( !vm.system ){
      				// 	vm.getSystem();
      				// }


      			},
				//extend $locale
				localExtend:function(){
					angular.extend($locale,{
						"DATETIME_FORMATS": {
							"AMPMS": [
								"AM",
								"PM"
							],
							"DAY": [
								"日",
								"一",
								"二",
								"三",
								"四",
								"五",
								"六"
							],
							"ERANAMES": [
								"Before Christ",
								"Anno Domini"
							],
							"ERAS": [
								"BC",
								"AD"
							],
							"FIRSTDAYOFWEEK": 6,
							"MONTH": [
								"一月",
								"二月",
								"三月",
								"四月",
								"五月",
								"六月",
								"七月",
								"八月",
								"九月",
								"十月",
								"十一月",
								"十二月"
							],
							"SHORTDAY": [
								"日",
								"一",
								"二",
								"三",
								"四",
								"五",
								"六"
							],
							"SHORTMONTH": [
								"一月",
								"二月",
								"三月",
								"四月",
								"五月",
								"六月",
								"七月",
								"八月",
								"九月",
								"十月",
								"十一月",
								"十二月"
							],
							"WEEKENDRANGE": [
								5,
								6
							],
							"fullDate": "EEEE, MMMM d, y",
							"longDate": "MMMM d, y",
							"medium": "MMM d, y h:mm:ss a",
							"mediumDate": "MMM d, y",
							"mediumTime": "h:mm:ss a",
							"short": "M/d/yy h:mm a",
							"shortDate": "M/d/yy",
							"shortTime": "h:mm a"
						},
						"NUMBER_FORMATS": {
							"CURRENCY_SYM": "$",
							"DECIMAL_SEP": ".",
							"GROUP_SEP": ",",
							"PATTERNS": [
								{
									"gSize": 3,
									"lgSize": 3,
									"maxFrac": 3,
									"minFrac": 0,
									"minInt": 1,
									"negPre": "-",
									"negSuf": "",
									"posPre": "",
									"posSuf": ""
								},
								{
									"gSize": 3,
									"lgSize": 3,
									"maxFrac": 2,
									"minFrac": 2,
									"minInt": 1,
									"negPre": "-\u00a4",
									"negSuf": "",
									"posPre": "\u00a4",
									"posSuf": ""
								}
							]
						},
						"id": "zh-cn",
						"pluralCat": function(n, opt_precision) {  var i = n | 0;  var vf = getVF(n, opt_precision);  if (i == 1 && vf.v == 0) {    return PLURAL_CATEGORY.ONE;  }  return PLURAL_CATEGORY.OTHER;}
					})
				},

      			changeAvater : function(){
      				var modalInstance = $uibModal.open({
				          templateUrl: "../views/mxu/common/tpl/avater.html",
				          controller: 'ctrl.avater',
				          windowClass :'avatar-wrap',
				          resolve: {
				           param: function () {
				              return vm.userInfo ;
				            }
				          }
			         });
			         modalInstance.result.then(function ( data ) {
			         	vm.userInfo = data;
			         	myUtils.storage.remove('user_info');
			         	myUtils.storage.set('user_info',vm.userInfo,vm.time);
			         });
      			},

				changePass: function () {
					var modalInstance = $uibModal.open({
						templateUrl: "../views/mxu/common/tpl/password.html",
						controller: 'ctrl.passWord',
						windowClass :'password-wrap',
						resolve: {
							param: function () {
								return '' ;
							}
						}
					});
				},

      			signOut : function(){
      				//退出登录
      				vm.signOut_loading = true;
      				http(config.getUrl('logout'))
      				.then(function( data ){
      					if( data && ( data.error_code || data.error_message)){
      						myUtils.tip({
	      						msg : data.error_message || config.error_tip
	      					},function(){
	      						vm.signOut_loading = false;
	      					})
      						return false;
      					}
      					if( data.data && data.data == 'success' ){
      						myUtils.storage.clear();

      						var param= {
								path   : window.CONFIG.cookiePath,
								domain : window.CONFIG.cookieDomain,
								expires:-1
      						};
      						myUtils.cookie('mxu_token','',param);
      						vm.signOut_loading = false;
      						$timeout( function(){
      							location.href= config.loginUrl;
      						},10)
      					}
      				},function(){
      					vm.signOut_loading = false;
      				});
      			}
      			
      		});
      		vm.init();
      	}
      	function crumbCtrl($rootScope,$timeout,$compile){
      		return {
      			restrict : 'AE',
				scope : {
					breadCrumbs : '=',
					breadParam : '=',
				},
				transclude: true,
				template :'<div class="bread-crumbs" >'+
								'<span ng-repeat="item in crumb">'
									+'<a ui-sref="{{item.url}}">{{item.title}}</a>'
								+'<span>'
							+'</div>',
				link : function( scope, element, attrs){
					scope.$watch('breadCrumbs',function( data,oldValue ){
						if( data ){
							element.find('.bread-crumbs').find('.third-item').remove();
							scope.crumb = [];
							var list = data.name.split('.'),listName ='';
							if( data.data && data.data.title ){
								listName = data.data.title.split('/');
							}
							var urlList = [];
							var curTitle = listName.slice(0,i);
							for( var i = 0;i<list.length+1;i++){
								var curList  = list.slice(0,i),url,title;
								if( curList && curList[0] ){
									url = curList.join('.');
									if( url && url !=='app' && urlList.indexOf(url) == -1){
										urlList.push(url);
									}
								}
							}
							if( curTitle.length < urlList.length){
								urlList.splice(0,urlList.length-curTitle.length);
							}
							angular.forEach(urlList,function( vv,kk ){
								var param = {
									url : vv
								}
								if( curTitle.length-1 == kk ){
									scope.$watch('breadParam',function( value){
										if( value.id && curTitle[kk].indexOf('新增') > -1 ){
											 curTitle[kk] =  curTitle[kk].replace('新增','编辑');
										}
										param.title = curTitle[kk]
									})
								}else{
									param.title = curTitle[kk]+' / '
								}
								if( scope.crumb.indexOf(param) == -1){
									 scope.crumb.push(param)
								}
							});
						}
					})
				}
      		}
      	}
      	
      	function avaterCtrl($scope,$uibModalInstance,$timeout,config,param,FileUploader,myUtils,http){
      		var vm = $scope.vm = {};
      		angular.extend( vm,{
      			init : function(){
      				vm.newInfo = angular.copy(param);
      				vm.initUpload();
      			},
      			initUpload:function( ){
      				//上传图片
					vm.uploader =  new FileUploader({
						url: config.getUrl('user_update'),
			            withCredentials : true,
					 });
		            vm.uploader.onAfterAddingAll = function(item) {
		            	var reader = new FileReader();
		            	 reader.readAsDataURL(item[0]._file);
		            	 reader.onload = function(){
		            	 	vm.newInfo.img = this.result;
		            	 	$scope.$apply(function(){
		            	 		vm.newInfo.img = vm.newInfo.img;
		            	 	})
					     }
		            };
		            vm.uploader.onCompleteItem = function(fileItem, response ){
		            	var data = response;
						if( data && ( data.error_code || data.error_message)){
							vm.error_tip = data.error_message || config.error_tip;
							return false;
						}
						if( data && data.data && data.data.filename ){
							vm.newInfo.avatar = data.data;
							vm.newInfo.img = myUtils.createImgsrc(data.data,{
								width:64,
								height:64
							});
							vm.img_loading = false;
							$timeout(function(){
								$uibModalInstance.close(vm.newInfo);
							},10)
						}
		            }
				},
				save : function(){
					vm.img_loading = true;
					vm.uploader.uploadAll();
				},
				cancel: function(){
					$uibModalInstance.dismiss('cancel');
				}
      		})
      		vm.init();
      	}

		function passWordCtrl($scope,$uibModalInstance,$timeout,config,param,myUtils,http){
		var vm = $scope.vm = {};
		angular.extend( vm,{
			init : function(){

			},
			save : function(){
				var url=config.getUrl('user_update');
				var param={
					old_password:vm.oldPassWord,
					password:vm.passWord,
					confirm_password:vm.PassWordAgain
				};
				http(url,param,'post')
						.then(function (data) {
							if( data && ( data.error_code || data.error_message)){
								vm.error_tip = data.error_message || config.error_tip;
								return false;
							}else {
								$uibModalInstance.dismiss('cancel');
							}
						})

			},
			cancel: function(){
				$uibModalInstance.dismiss('cancel');
			}
		});
		vm.init();
	}


})();